import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/prevent_repeated_event.dart';
import 'package:finance_app/src/entities/address_entity.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'default_bottom_sheet.dart';

/// 选择地址
///
/// 返回地址
showAddressBottomSheet(BuildContext context, AddressEntity currentSelect,
    Future<List<AddressEntity>> onLoadingAddress(String text)) async {
  AddressEntity _currentSelectCode = currentSelect;

  await showDefaultBottomSheet(
    context,
    child: AddressWidget(
      onLoadingAddress: onLoadingAddress,
      currentSelect: currentSelect,
      selectCallBack: (data) {
        _currentSelectCode = data;
      },
    ),
    title: S.current.address_codes,
    isScrollControlled: true,
  );
  return _currentSelectCode;
}

class AddressWidget extends StatefulWidget {
  final AddressEntity currentSelect;
  final ValueChanged<AddressEntity> selectCallBack;
  final Future<List<AddressEntity>> Function(String text) onLoadingAddress;

  AddressWidget(
      {Key key, this.currentSelect, this.selectCallBack, this.onLoadingAddress})
      : super(key: key);

  @override
  _AddressWidgetState createState() => _AddressWidgetState();
}

class _AddressWidgetState extends State<AddressWidget> {
  TextEditingController _searchController = TextEditingController();
  FocusNode _searchFocusNode = FocusNode();
  AddressEntity _currentSelect;
  List<AddressEntity> addressList = [];
  PreventRepeatedEvent event = PreventRepeatedEvent();

  String lastSearchText;

  @override
  void initState() {
    super.initState();
    _currentSelect = widget.currentSelect;
    _searchController.addListener(_handleSearchInput);
    event.addEventListener((data) async {
      if (lastSearchText == null && data.length == 0) return;
      if (lastSearchText == data) return;
      if (mounted)
        setState(() {
          addressList = null;
        });
      lastSearchText = data;
      final _addressList = await widget.onLoadingAddress(lastSearchText);
      if (mounted)
        setState(() {
          addressList = _addressList ?? [];
        });
    });
  }

  void _handleSearchInput() {
    event.sendEvent(_searchController.text);
  }

  @override
  void dispose() {
    super.dispose();
    _searchController.dispose();
    _searchFocusNode.dispose();
    event.cancel();
  }

  void onChangeSelect(AddressEntity value) {
    if (value != _currentSelect) {
      setState(() {
        _currentSelect = value;
      });
      widget.selectCallBack?.call(_currentSelect);
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height * 0.30;
    return Column(
      children: [
        AppSpaces.h10,
        SearchInputField(
          key: ValueKey("Search Input"),
          controller: _searchController,
          focusNode: _searchFocusNode,
        ),
        AppSpaces.h10,
        SizedBox(
          height: height,
          child: _buildAddressItem(),
        ),
      ],
    );
  }

  Widget _buildAddressItem() {
    if (addressList == null) {
      return BaseConfig.pageBase.buildLoadingWidget(context);
    }
    if (addressList.length > 0) {
      return CupertinoScrollbar(
        child: CustomScrollView(
          slivers: [
            SliverList(
                delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {
                final address = addressList[index];
                return PressedOpacityButton(
                  onPressed: () {
                    onChangeSelect(address);
                  },
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(35),
                    vertical: getDp(13),
                  ),
                  border: Border(
                      bottom:
                          BorderSide(width: getDp(0.5), color: aceGrayColor)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        address.name,
                        style: TextStyle(
                          color: aceBlackColor,
                          fontSize: getSp(16),
                          fontWeight: FontWeight.w700,
                          height: 14 / 16,
                        ),
                      ),
                      SizedBox(
                        height: getDp(4),
                      ),
                      Text(
                        '${address.address} ${address.code}',
                        style: TextStyle(
                          color: aceDarkGrayColor,
                          fontSize: getSp(14),
                          fontWeight: FontWeight.w400,
                          height: 1,
                        ),
                      ),
                    ],
                  ),
                );
              },
              childCount: addressList.length,
            ))
          ],
        ),
      );
    }
    return Container();
  }
}
